<?php
namespace control;
/*
*委外需求计划类
*/

class outsourceDemandClass extends adIndexClass
{
    private const page = 'outsourceDemand';
    private const title = '委外需求计划';
    private const table = 'outsource_demands';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'sourceDate'          => [
                        'name'  => '单据日期',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'sourceType' => [
                        'name'  => "源单类型",
                        'width' => 100,
                    ],
                    'sourceNo'  => [
                        'name'  => "源单号",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'subject'         => [
                        'name'  => '存货类别',
                        'width' => 100,
                    ],
                    'code'          => [
                        'name'  => '物料编码',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'materialName'          => [
                        'name'  => '物料名称',
                        'width' => 180,
                    ],
                    'model'          => [
                        'name'  => '规格型号',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'unit'          => [
                        'name'  => '单位',
                        'width' => 100,
                    ],
                    'num'          => [
                        'name'  => '订单数量',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'stockNum'          => [
                        'name'  => '库存数量',
                        'width' => 100,
                    ],
                    'productNum'          => [
                        'name'  => '已生产数量',
                        'width' => 100,
                    ],
                    'residue'          => [
                        'name'  => '剩余待生产数量',
                        'width' => 120,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        $material = new materialClass();
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "状态" => checkbox(array('name'=>'isClear','value'=>['未清','已清'],'checked'=>['未清'])),
                ],
                [
                    "源单号" => text(array("name" => "orderNo")),
                    "存货类别"   => select(array('name'=>'subject','title'=>'存货类别','option'=>$material->checkOption)),
                    '物料编码' => text(array("name" => "code")),
                ],
                [
                    '物料名称' => text(array("name" => "materialName")),
                    '来源'  => select(array('name'=>'source','option'=>$material->sourceOption)),
                    "供应控制" => select(array('name'=>'supplyControl','option'=>$material->controlOption)),
                ],
                [
                    '单据日期' => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button='';
        if ($this->power(self::page,'edit')){
            $button = "<span class='spanButton' onclick=\"commitOrder()\">生成委外加工单</span>
                        <span class='spanButton' onclick=\"layer('".self::page."','mark','listForm')\">标记为已清</span>".componentClass::tipComponent('委外加工数量已经满足可标记为已清');//生产数量是否已经满足了销售单数量要求
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "a.sourceNo" => $this->post('orderNo'),//证件编号
            "c.name" => $this->post('materialName'),
            "c.code" => $this->post('code'),
            'c.supplyControl'=>$this->post('supplyControl')
        );
        //全等查询数组
        $equal = array(
            "a.coid"=>self::$coid,
            "c.subject" => $this->post('subject'),
            "c.source" => $this->post('source'),
        );
        $and ='';
        if ($this->post('createTime')) {
            //单据日期
            $and.=self::timeComparison($this->post('createTime'),field: 'a.sourceDate');
        }
        if ($this->post('isClear')) {
            $isClear = [];
            if (in_array('已清',$this->post('isClear'))){
                $isClear[] = 1;
            }
            if (in_array('未清',$this->post('isClear'))){
                $isClear[] = 0;
            }
            //单据日期
            $and.=" and isClear in ('".implode("','",$isClear)."')";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'a.sourceDate desc,a.time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array(
            "table" => self::table." as a join  material as c on c.id = a.materialId",
            'field'=>"a.*,c.code,c.name as materialName,c.model,c.subject,c.unit as mainUnit",
            "where" => $where,
            "order" => $orderBy['orderBy']
        ));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
            );
            //已生产数量
            $productNum = 0;
            $outsource_in_order_detail = find(array(
                'table'=>"outsource_in_order as a join outsource_in_order_detail as b on a.id = b.orderId",
                'where'=>"a.state = '已确认' and a.coid = '".self::$coid."' and b.sourceId !='' and b.sourceId in (select id from outsource_process_material where sourceId = '$array[id]')",
                'field'=>"b.num,b.unit,b.materialId"
            ));
            foreach ($outsource_in_order_detail['array'] as $val){
                $productNum +=machiningOrderClass::material_num_change($val['materialId'],$val['unit'],$array['unit'],$val['num']);
            }
            $machining_in_detail = find(array(
                'table'=>"machining_in_order as a join machining_in_order_detail as b on a.id = b.orderId",
                'where'=>"a.state = '已确认' and a.coid = '".self::$coid."' and b.sourceId !='' and b.sourceId in (select id from machining_order_mx where sourceId = '$array[targetId]')",
                'field'=>"b.num,b.unit,b.materialId"));
            foreach ($machining_in_detail['array'] as $val){
                $productNum +=machiningOrderClass::material_num_change($val['materialId'],$val['unit'],$array['unit'],$val['num']);
            }
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "num":
                        $row[] = self::lostZero($array['num'],'numPrecision');
                        break;
                    case "stockNum":
                        $stockNum = inventoryBalanceClass::inventoryNum($array['materialId']);//库存数量
                        $row[] = machiningOrderClass::material_num_change($array['materialId'],$array['mainUnit'],$array['unit'],$stockNum);
                        break;
                    case "productNum":
                        $row[] = $productNum;
                        break;
                    case "residue":
                        $row[] = $array['num']-$productNum;
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $numTotal = find([
            'table'  => self::table." as a join  material as c on c.id = a.materialId",
            'single' => $where,
            'field'  => "ifnull(sum(a.num),0) as num",
        ]);
        //已生产数量
        $productNum = 0;
        $outsource_in_order_detail = find(array(
            'table'=>"outsource_in_order as ord join outsource_in_order_detail as detail on ord.id = detail.orderId join outsource_process_material as process on process.id = detail.sourceId join outsource_demands as demands on demands.id = process.sourceId",
            'where'=>"ord.state = '已确认' and ord.coid = '".self::$coid."' and demands.id in (select a.id from ".self::table." as a join  material as c on c.id = a.materialId where 1=1 {$where})",
            'field'=>"detail.num,detail.unit,detail.materialId,demands.unit as toUnit"
        ));
        foreach ($outsource_in_order_detail['array'] as $val){
            $productNum +=machiningOrderClass::material_num_change($val['materialId'],$val['unit'],$val['toUnit'],$val['num']);
        }
        $machining_in_detail = find(array(
            'table'=>"machining_in_order as ord join machining_in_order_detail as detail on ord.id = detail.orderId join machining_order_mx as mx on mx.id = detail.sourceId join outsource_demands as demands on demands.targetId = mx.sourceId",
            'where'=>"ord.state = '已确认' and ord.coid = '".self::$coid."' and demands.id in (select a.id from ".self::table." as a join  material as c on c.id = a.materialId where 1=1 {$where})",
            'field'=>"detail.num,detail.unit,detail.materialId,demands.unit as toUnit"));
        foreach ($machining_in_detail['array'] as $val){
            $productNum +=machiningOrderClass::material_num_change($val['materialId'],$val['unit'],$val['toUnit'],$val['num']);
        }
        $total       = [
            'num'         => self::lostZero($numTotal['num'], 'numPrecision'),
            'productNum'         => self::lostZero($productNum, 'numPrecision'),
            'residue'         => self::formattingFigure($numTotal['num']-$productNum, 'numPrecision'),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = "<form name='listForm'>" . $li . "</form>".$this->js() . $page['button'] . clear;
        return json_encode($json, 320);
    }
    public function mark(): bool|string
    {
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                "提示：" => "是否标记所选数据为已清？",
            ),
        )));
        //返回
        return $this->layer(array("title" => "提示", "height" => 165, "html" => $html, 'formTwo' => 'listForm'));
    }
    public function markEdit(): bool|string
    {
        $listId = $this->post('listId');
        if (static::is_null_array($listId)){
            $json['warn'] = '请选择数据';
        }elseif (!$this->power(self::page,'edit')){
            $json['warn'] = '您还没有'.self::title.'的编辑权限';
        }else{
            $x = 0;
            $text = '';
            foreach ($listId as $id){
                $demands = query(self::table,"id = '$id'");
                $warn = update(array('table'=>self::table,'field'=>['isClear'=>1],'where'=>"id = '$id'"));
                $material = query('material',"id = '$demands[materialId]'");
                if ($warn =='更新成功'){
                    $x++;
                    $text.="委外需求【{$demands['id']}】,产品【{$material['code']}-{$material['name']}-{$material['model']}】标记为已清<br>";
                }else{
                    $text.="委外需求【{$demands['id']}】,产品【{$material['code']}-{$material['name']}-{$material['model']}】标记已清失败<br>";
                }
            }
            $text=$this->control['name'].'标记了委外需求如下：'.$text;
            $this->logText(["type" => self::page, "text" => $text]);
            $json['warn'] = 2;
            $_SESSION['warn'] = "成功标记了{$x}条数据";
        }
        return json_encode($json,320);
    }
    public function js(): string
    {
        return <<<eof
<script>
//生成生产计划单
function commitOrder(){
    cxDialog('是否确认生成委外加工单?', () => {
            let arr = [];
            $("[name='listForm'] input[type=checkbox]:checked").each(function () {
                if ($(this).val() && $(this).val() !== 'on') {
                    arr.push($(this).val());
                }
            });
            if (arr.length ===0){
                msg('请选择数据','error')
                return false;
            }
            let listId = arr.join(",");
            newIframe('委外加工单',root+'control/adIndex.html?cla=outsourceProcess&fun=edit&source=outsourceDemand&listId='+listId,'供应链','委外')
    }, () => {
      // click no callback
    });
}

</script>
eof;

    }



}
